#include<iostream>
#include<vector>
#include<string>
#include<unistd.h>
#include<pthread.h>

using namespace std;

#define NUM 5


pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int tickets = 1000;

struct data
{
    data(int i)
    :num(i)
    {}
    int num;
};


void* mypthread(void* args)
{   


    data* t = static_cast<data*>(args);
    pthread_mutex_lock(&mutex);

    while(true)
    {
        if(tickets)
        {
            cout << "thread_num: " << t->num << " ticket: " << tickets <<endl;
            tickets--;
        }
        else if(tickets < 0)
        {
            break;
        }
    }
    pthread_mutex_unlock(&mutex);
    return nullptr;
}

int main()
{
    vector<pthread_t> tids;
    for(int i = 0 ; i < NUM; i++)
    {
        data* t = new data(i);
        pthread_t tid;
        pthread_create(&tid,nullptr,mypthread,t);
        tids.push_back(tid);

    }
    cout << "休眠3秒" <<endl;
    sleep(3);
    for(int i = 0 ;i < NUM ;i++)
    {
        cout << "线程退出" <<endl;
        pthread_join(tids[i],nullptr);
    }
    return 0;
}